package java.com.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author ljj
 */
public class SyncUtil<T> {
	/**
	 * 内部持有一个 CountDownLatch
	 */
	private CountDownLatch countDownLatch;
	
	/**
	 * result 可能被多线程读写，添加同步处理
	 */
	private final List<T> result = Collections.synchronizedList(new ArrayList<>());
	
	
	public SyncUtil(int taskCount) {
		this.countDownLatch = new CountDownLatch(taskCount);
	}
	
	/**
	 * 用 await() 等待所有任务全部完成，再返回, 必须在其他地方调用 countDownLatch.countDown();
	 */
	public List<T> get() throws InterruptedException {
		countDownLatch.await();
		return this.result;
	}
	
	/**
	 * 带超时的 get()
	 */
	public List<T> get(long timeout, TimeUnit timeUnit) throws Exception {
		if (countDownLatch.await(timeout, timeUnit)) {
			return this.result;
		} else {
			throw new RuntimeException("超时");
		}
	}
	
	/**
	 * 添加返回结果
	 */
	public void addResult(T resultMember) {
		result.add(resultMember);
		countDownLatch.countDown();
	}
	
	public void addResult(List<T> resultMembers) {
		result.addAll(resultMembers);
		countDownLatch.countDown();
	}
}
